package cn.hongsw.file.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author :hongsw
 * @date :2021-08-11 15:12
 */
@RestController
public class DownloadController {
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        File file = new File("E:\\下载demo.txt");
        InputStream inputStream = new FileInputStream(file);
        //设置content-disposition响应头控制浏览器以下载的形式打开文件，中文文件名要使用URLEncoder.encode方法进行编码，否则会出现文件名乱码
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("下载demo.txt", "UTF-8"));
        response.setContentType("application/octet-stream");
        int len;
        ServletOutputStream out = response.getOutputStream();
        // 缓冲区
        byte[] buffer = new byte[1024];
        while ((len = inputStream.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        inputStream.close();
        out.flush();
        out.close();
    }
}
